package net.mmgg.android.bm;

import java.util.HashMap;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ScrollView;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;

public class TabsActivity extends TabActivity {
	private TextView textView;
	private TextView textErrorView;
	private ScrollView scrollView;
	private TabSpec tabSpec;
	private int num;
	private boolean isOver = false;

	private ProgressDialog progressDialog = null; 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Intent mainIntent = getIntent();
		super.onCreate(savedInstanceState);
		// 获得TabHost对象
		TabHost tah = getTabHost();
		num = mainIntent.getIntExtra("num", 1);

		LayoutInflater.from(this).inflate(R.layout.activity_tabs, tah.getTabContentView(), true);
		textView = (TextView) findViewById(R.id.textView);
		textErrorView = (TextView) findViewById(R.id.textErrorView);
		scrollView = (ScrollView) findViewById(R.id.scrollView);
		// 设置Tab标签的内容和显示内容
		tah.addTab(tah.newTabSpec("tab1").setIndicator("实时日志").setContent(R.id.textView));
		tabSpec = tah.newTabSpec("tab2").setIndicator("运行日志").setContent(R.id.textErrorView);
		tah.addTab(tabSpec);
		// textView.append("6228 4808 0087 8536 716\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n6228 4808 0087 8536 716\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n6228 4808 0087 8536 716\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
		execute();
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO 接收消息并且去更新UI线程上的控件内容
			if (msg.what == 0) {
				textView.append(String.valueOf(msg.obj));
				scrollView.scrollTo(0, textView.getHeight());
			}
			if (msg.what == 1) {
				textErrorView.append(String.valueOf(msg.obj));
				Config cfg = (Config) getApplication();
				cfg.setLog(textErrorView.getText().toString());
			}
			super.handleMessage(msg);
		}
	};

	private void execute() {
		progressDialog = ProgressDialog.show(TabsActivity.this, "请稍后", "正在准备数据,请稍候！");
		final Config cfg = (Config) getApplication();

		textView.setTextColor(android.graphics.Color.BLUE);
		textErrorView.setTextColor(android.graphics.Color.RED);
		Config cfgText = (Config) getApplication();
		textErrorView.setText(cfgText.getLog());

		final ConfigUtil configUtil = new ConfigUtil();
		final SearchDao searchDao=new SearchDao();
		new Thread(new Runnable() {
			@Override
			public void run() {
				Looper.prepare();
				Thread.currentThread().setName("信息");
				//log(handler,"请稍后...");
				
				Map<String, String> param = new HashMap<String, String>();
				String str = CustomerHttpClient.get("http://www.baidu.com/");
				if (null == str) {
					Toast.makeText(getApplicationContext(), "打开百度失败!", Toast.LENGTH_LONG).show();
					return;
				}
				Document doc = Jsoup.parseBodyFragment(str);
				Element em = doc.select("form").first();
				Elements inputs = em.select("input"); // 輸入
				String action = em.attr("action");
				Log.i("action===", action);
				for (Element element : inputs) {
					String val = element.val();
					if (null == element.attr("name") || "".equals(element.attr("name"))) {

					} else {
						param.put(element.attr("name"), val);
					}
					Log.i(element.attr("name") + "===", val);
				}
				DataBean dataBean = configUtil.getData(cfg);
				if (null == dataBean) {
					Toast.makeText(getApplicationContext(), "从服务器获取关键词失败!", Toast.LENGTH_LONG).show();
					return;
				}
				progressDialog.dismiss();
				searchDao.request(action, param, dataBean, num,handler);
			}
		}).start();
	}

	@Override
	public void onBackPressed() {
		finish();
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			Toast.makeText(getApplicationContext(), "日志清除成功!", Toast.LENGTH_LONG).show();
			Config cfg = (Config) getApplication();
			cfg.setLog("");
			textErrorView.setText("");
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	private void log(Handler handler, String message, boolean... isError) {

		Message msg = new Message();
		if (isError.length > 0 && isError[0]) {
			msg.what = 1;
		} else {
			msg.what = 0;
		}
		msg.obj = Thread.currentThread().getName() + ">>>" + message + "\n\n";
		handler.sendMessage(msg);

	}
}
